#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : UserApi.py
@Time : 2025/2/5 11:48
@Author: Wangwc
@Describe:  用户管理相关接口封装
"""
import time
from datetime import datetime

import requests

from utils.requests_tools import HttpRequest, check_response, retry_func
from utils.login import Login
from commons.logger import log

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = 'user.ini'

assert_message = {'code': 200, 'msg': 'success'}


#@check_response装饰器进行代码解耦，用于提取接口放回数据和进行接口断言

class UserApi:

    def __init__(self, u_token, configname=config_name):
        self.http = HttpRequest(configname, u_token=u_token)

    @check_response(ext="data.list", check=assert_message)
    def get_user_list(self):
        """
        获取用户列表信息
        :return:用户列表信息
        """
        log.debug(f"开始获取用户列表信息")
        path = "/ugreen/v1/user/list"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户列表信息过程中出现异常，异常信息: {e}")
            raise

    def get_user_name_list(self):
        """
        获取用户名称列表信息
        :return:用户列表信息
        """
        log.debug(f"开始获取用户名称列表信息")
        username_list = []
        try:
            user_list = self.get_user_list()
            for user in user_list:
                if user.get('username'):
                    username_list.append(user.get('username'))
            return username_list
        except Exception as e:
            log.error(f"在获取用户列表信息过程中出现异常，异常信息: {e}")
            raise

    def get_user_uid_by_username(self, username: str) -> int | None:
        """
        根据用户名获取用户uid
        :param username: 用户名
        :return: 用户uid，如果未找到则返回 None
        """
        try:
            user_list = self.get_user_list()
            for user in user_list:
                if user.get('username') == username:
                    return user.get('uid')
            # 遍历完整个用户列表都没找到目标用户，输出日志并返回 None
            log.error(f"在获取用户列表信息过程中，没有找到用户名为{username}的用户")
            return None
        except Exception as e:
            log.error(f"获取用户列表时出现异常: {e}")
            return None

    @check_response(ext="data", check=assert_message)
    def user_rule_password(self, username, password):
        """
        用户规则密码
        :param username: 用户名
        :param password: 密码
        :return:
        """
        path = "/ugreen/v1/user/rule/password"
        request_data = {"username": username, "password": password}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在用户规则密码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def check_user_name(self, username):
        """
        检查用户名是否存在
        :param username: 用户名
        :return:
        """
        path = "/ugreen/v1/user/name/check"
        data = {"username": username}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在检查用户名是否存在过程中出现异常，异常信息: {e}")
            raise

    # @check_response(ext="data", check=assert_message)
    def create_user(self, username, password, email='', description='', role='admin', groups=[], enable_home_dir=True,
                    deny_change_pwd=False, dir_quota=0, unit=1):
        """
        创建用户
        :return: 用户id
        """
        log.debug(f"开始创建用户{username}")
        path = "/ugreen/v1/user/create"
        request_data = {"username": username, "password": password, "email": email, "description": description,
                        "role": role, "groups": groups, "enable_home_dir": enable_home_dir,
                        "deny_change_pwd": deny_change_pwd, "dir_quota": dir_quota, "unit": unit}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在创建用户过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_user_information(self, uid):
        """
        根据用户id获取用户基本信息
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始获取用户基本信息，用户id：{uid}")
        path = f"/ugreen/v1/user/uid/{uid}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在根据用户id获取用户基本信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_user_permission(self, uid):
        """
        获取用户共享文件夹权限
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始获取用户共享文件夹权限，用户id：{uid}")
        path = f"/ugreen/v1/user/permission/{uid}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户共享文件夹权限过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_user_group_permission(self, role, gids):
        """
        获取用户组共享文件夹权限
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始获取用户组共享文件夹权限")
        path = f"/ugreen/v1/group/gids/permission"
        request_data = {"role": role, "gids": gids}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在获取用户共享文件夹权限过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_user_permission(self, uid, path_list):
        """
        给用户设置指定共享文件夹权限
        :param uid: 用户id
        :param path_list: 设置的权限列表
        :return:
        """
        log.debug(f"开始给用户设置指定共享文件夹权限，用户id：{uid}")
        path = f"/ugreen/v1/user/permission/{uid}"
        request_data = {"list": path_list}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在给用户设置指定共享文件夹权限过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def edit_user(self, username, uid, role='admin', groups=[], email='', description='', enable_home_dir=True,
                  deny_change_pwd=False, dir_quota=0, unit=1, expire_time=-1, expire_date='', **kwargs):
        """
        编辑用户信息
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始编辑用户信息，用户id：{uid}")
        path = "/ugreen/v1/user/edit"
        request_data = {"username": username, "role": role, "groups": groups, "uid": uid, "email": email,
                        "description": description,
                        "enable_home_dir": enable_home_dir, "deny_change_pwd": deny_change_pwd, "dir_quota": dir_quota,
                        "unit": unit,
                        "expire_time": expire_time, "expire_date": expire_date}

        # 检查是否传入了 password 参数
        if 'password' in kwargs:
            request_data['password'] = kwargs['password']

        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在编辑用户信息过程中出现异常，异常信息: {e}")
            raise

    def get_user_headpic(self, uid):
        """
        获取用户头像流
        :param: uid 用户id  1001
        :param: time: 当前时间戳
        :return:
        """
        log.debug("开始执行获取用户头像操作")
        path = f'/ugreen/v1/user/headpic/stream/{uid}'
        params = {"t": int(time.time() * 1000)}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在获取用户头像过程中出现异常，异常信息: {e}")
            raise

    def get_headpic_stream(self, icon):
        """
        获取头像图片流
        :param: icon 01.png
        :return:
        """
        log.debug("开始执行获取头像图片流操作")
        path = f'/ugreen/v1/user/headpic/stream/{icon}'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取头像图片流过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.list", check=assert_message)
    def get_user_headpic_list(self):
        """
        获取用户头像列表
        :return:
        """
        log.debug("开始执行获取默认头像列表操作")
        path = '/ugreen/v1/user/headpic/list'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取默认头像列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_user_headpic(self, uid, icon=None, file=None):
        """
        更换用户头像
        :param: uid 用户id  1001
        :param: icon 头像  02.png
        :param: file:
        :return:
        """
        log.debug("开始执行更换用户头像操作")
        path = f'/ugreen/v1/user/change/headpic/{uid}'
        data = {}
        if icon is not None:
            data["icon"] = icon
        elif file is not None:
            data["file"] = file
        else:
            raise ValueError("icon和file参数不能同时为空，必须有一个有值")
        try:
            response = self.http.post(path, data=data)
            return response
        except Exception as e:
            log.error(f"在获取默认头像列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def search_user(self, keyword, flag=0, status=0):
        """
        搜索用户
        :param keyword: 关键字
        :param flag: 0:搜索用户 1:搜索群组
        :param status: 0:搜索所有用户 1:搜索在线用户
        :return:
        """
        log.debug("开始执行搜索用户操作")
        path = '/ugreen/v1/user/search'
        request_data = {"keyword": keyword, "flag": flag, "status": status}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在搜索用户过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_user_directory_quota(self):
        """
        获取用户存储限额信息
        :return:
        """
        log.debug("开始执行获取用户存储限额信息操作")
        path = '/ugreen/v2/user/directory/quota'
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户存储限额信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def change_user_password(self, uid, password, old_password):
        """
        更改用户密码
        :param uid: 用户id  1001
        :param password: 新密码(加密后的密码）
        :param old_password: 旧密码(加密后的密码）
        :return:
        """
        log.debug("开始执行更改用户密码操作")
        path = '/ugreen/v1/user/change/passwd'
        request_data = {"uid": uid, "password": password, "old_password": old_password}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在更改用户密码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def delete_user(self, uid, x_curpass_token):
        """
        删除用户
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始删除用户，用户id：{uid}")
        path = "/ugreen/v1/user/delete"
        request_data = [uid]
        headers = {"x-curpass-token": x_curpass_token}
        try:
            response = self.http.delete(path, json=request_data, headers=headers)
            return response
        except Exception as e:
            log.error(f"在删除用户过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_uglink_status(self):
        """
        获取uglink状态
        :return:
        """
        log.debug("开始执行获取uglink状态操作")
        path = "/ugreen/v1/connect/uglink/status"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取uglink状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_invite_state(self, uid):
        """
        获取邀请码
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始获取邀请码，用户id：{uid}")
        path = f"/ugreen/v1/user/invite/state/{uid}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取邀请码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def check_username(self, internalDomain, invite_code, username):
        """
        校验用户名是否存在
        :param uid: 用户id
        :return:
        """
        log.debug(f"校验用户名是否存在，用户名：{username}")
        path = f"https://{internalDomain}/ugreen/v1/user/__token/name/check"
        params = {"code": invite_code}
        data = {"name": username}
        try:
            response = self.http.post(path, json=data, params=params)
            return response
        except Exception as e:
            log.error(f"在获取邀请码过程中出现异常，异常信息: {e}")
            raise

    def get_invite_rsatoken(self, internalDomain, username):
        """
        获取邀请用户时的rsatoken
        :param uid: 用户id
        :return:
        """
        log.debug(f"开始获取邀请用户时的rsatoken，用户名：{username}")
        path = f"https://{internalDomain}/ugreen/v1/verify/check"
        data = {"username": username}
        try:
            result = self.http.post(path, json=data)
            return result.headers.get('X-Rsa-Token')
        except Exception as e:
            log.error(f"在获取邀请码过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def user_invite(self, internalDomain, invite_code, username, password, **kwargs):
        """
        用户申请
        :param internalDomain: 内部域名
        :param invite_code: 邀请码
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数，如email、reason等
        :return:
        """
        log.debug(f"开始申请用户操作，用户名：{username}")
        path = f"https://{internalDomain}/ugreen/v1/user/__token/invite/ask"
        params = {"code": invite_code}
        data = {"username": username, "password": password}
        if kwargs:
            data.update(kwargs)
        try:
            response = self.http.post(path, json=data, params=params)
            return response
        except Exception as e:
            log.error(f"在用户申请过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_user_invite_list(self):
        """
        获取用户申请列表
        :return:
        """
        log.debug(f"开始获取用户申请列表操作")
        path = "/ugreen/v1/user/invite/list"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户申请列表过程中出现异常，异常信息: {e}")
            raise

    def get_invite_id_by_username(self, username):
        """
        根据用户名称获取邀请ID
        :return:
        """
        log.debug(f"开始根据用户名称获取邀请ID操作")
        try:
            invite_list = self.get_user_invite_list()
            for invite in invite_list:
                if invite.get('username') == username:
                    return invite.get('ID')
            log.warning(f"未找到用户名为{username}的邀请信息")
            return None
        except Exception as e:
            log.error(f"在根据用户名称获取邀请ID过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def agree_invite(self, id, role='admin', groups=[], email='', description='', enable_home_dir=True, dir_quota=0,
                     unit=1):
        """
        审批用户申请
        :param id : 用户申请id
        :param role: 用户角色
        :param groups: 用户组
        :param email: 用户邮箱
        :param description: 用户描述
        :param enable_home_dir: 是否启用家目录
        :param dir_quota: 家目录配额
        :param unit: 配额单位
        :return:
        """
        log.debug(f"开始审批用户申请操作")
        path = "/ugreen/v1/user/invite/agree"
        data = {"id": id, "account": {"role": role, "groups": groups, "email": email, "description": description,
                                      "enable_home_dir": enable_home_dir, "dir_quota": dir_quota, "unit": unit}}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在用户申请过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def delete_invite(self, id):
        """
        删除用户申请
        :param id : 用户申请id
        :return:
        """
        log.debug(f"开始删除用户申请操作")
        path = f"/ugreen/v1/user/invite/{id}"
        try:
            response = self.http.delete(path)
            return response
        except Exception as e:
            log.error(f"在删除用户申请过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_agree_user_list(self):
        """
        获取已加入的用户申请列表
        :return:
        """
        log.debug(f"开始获取用户申请列表操作")
        path = "/ugreen/v1/user/invite/agree/list"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取已加入的用户申请列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.list", check=assert_message)
    def get_user_group_list(self):
        """
        获取用户组列表信息
        :return:用户组列表信息
        """
        log.debug(f"开始获取用户组列表信息")
        path = "/ugreen/v1/group/list"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取用户组列表信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_group_info_by_id(self, group_id):
        """
        根据用户组id获取用户组信息
        :return:用户组列表信息
        """
        log.debug(f"开始根据用户组id获取用户组信息，用户组id：{group_id}")
        path = f"/ugreen/v1/group/info/{group_id}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在根据用户组id获取用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_group_permission_by_id(self, group_id):
        """
        根据用户组id获取用户组共享文件夹权限
        :return:用户组列表信息
        """
        log.debug(f"开始根据用户组id获取用户组共享文件夹权限，用户组id：{group_id}")
        path = f"/ugreen/v1/group/permission/{group_id}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在根据用户组id获取用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_group_permission(self, group_id, list):
        """
        给用户组设置共享文件夹权限
        :param group_id:用户组id
        :param list:权限列表 [{"path":"/volume1/autotest","permission":7},{"path":"/volume1/test2","permission":-1}]
        :return:
        """
        log.debug(f"开始给用户组设置共享文件夹权限，用户组id：{group_id}")
        path = f"/ugreen/v1/group/permission/{group_id}"
        data = {"list": list}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在根据用户组id获取用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def create_user_group(self, groupname, **kwargs):
        """
        创建用户组
        :param groupname: 用户组名称
        :param kwargs: description: 用户组描述 users: 用户列表 [{"name":"test"},{"name":"test4"}]
        :return:
        """
        log.debug(f"开始创建用户组")
        path = "/ugreen/v1/group/create"
        request_data = {"groupname": groupname}
        if kwargs:
            request_data.update(kwargs)
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在创建用户组过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def edit_user_group(self, groupname, gid, **kwargs):
        """
        编辑用户组信息
        :param groupname: 用户组名称
        :param gid:用户组id
        :param kwargs: description: 用户组描述 users: 用户列表 [{"name":"test"},{"name":"test4"}]
        :return:
        """
        log.debug(f"开始编辑用户组信息")
        path = "/ugreen/v1/group/edit"
        request_data = {"groupname": groupname, "gid": gid}
        if kwargs:
            request_data.update(kwargs)
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在创建用户组过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def search_user_group(self, keyword, flag=0):
        """
        搜索用户组信息
        :param keyword: 搜索关键字
        :return:
        """
        log.debug(f"开始搜索用户组信息")
        path = "/ugreen/v1/group/search"
        request_data = {"keyword": keyword, "flag": flag}
        try:
            response = self.http.post(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在搜索用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def delete_user_group(self, group_id):
        """
        删除用户组信息
        :param group_id: 用户组id
        :return:
        """
        log.debug(f"开始删除用户组信息")
        path = "/ugreen/v1/group/delete"
        request_data = [group_id]
        try:
            response = self.http.delete(path, json=request_data)
            return response
        except Exception as e:
            log.error(f"在删除用户组信息过程中出现异常，异常信息: {e}")
            raise

    def get_gid_by_groupname(self, groupname):
        """
        根据用户组名称获取用户组id
        :param groupname:
        :return:
        """
        log.debug(f"开始根据用户组名称获取用户组id")
        try:
            group_list = self.get_user_group_list()
            for group in group_list:
                if group.get("groupname") == groupname:
                    return group.get("gid")
            log.info(f"未找到用户组名称为{groupname}的用户组id")
            return None
        except Exception as e:
            log.error(f"在根据用户组名称获取用户组id过程中出现异常，异常信息: {e}")

    def get_group_info_by_gid(self, gid):
        """
        根据用户组id获取该组信息
        :param gid:用户组id
        :return:
        """
        log.debug(f"开始根据用户组id获取该组信息")
        try:
            group_list = self.get_user_group_list()
            for group in group_list:
                if group.get("gid") == gid:
                    return group
            log.info(f"未找到用户组id为{gid}的用户组信息")
            return None
        except Exception as e:
            log.error(f"在根据用户组id获取该组信息过程中出现异常，异常信息: {e}")

    @check_response(ext="data", check=assert_message)
    def get_global_config(self):
        """
        获取高级设置配置信息
        :return:
        """
        log.debug(f"开始获取高级设置配置信息")
        path = "/ugreen/v1/user/config/global"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取高级设置配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def set_global_config(self, disable_contain_key=False, disable_common_pwd=False, must_contain_case=False,
                          must_contain_num=False, must_contain_special_char=False, min_length=6):
        """
        设置高级设置配置信息
        :return:
        """
        log.debug(f"开始设置高级设置配置信息")
        path = "/ugreen/v1/user/config/global"
        data = {"disable_contain_key": disable_contain_key, "disable_common_pwd": disable_common_pwd,
                "must_contain_case": must_contain_case, "must_contain_num": must_contain_num,
                "must_contain_special_char": must_contain_special_char, "min_length": min_length}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在设置高级设置配置信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def import_excel_user_data(self, file_data):
        """
        导入用户信息表
        :param file_data:信息表格的二进制数据
        :return: 用户列表信息
        """
        log.debug(f"开始导入用户信息表")
        path = "/ugreen/v1/user/import"
        data = {'file': file_data}
        try:
            response = self.http.post(path, files=data)
            return response
        except Exception as e:
            log.error(f"在导入用户信息表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def import_user_commit(self, force_change_pwd=False, overwrite=False, list=[]):
        """
        正式提交导入客户信息
        :param force_change_pwd: 是否强制修改密码
        :param overwrite: 是否覆盖
        :param list: 用户列表信息，从import_excel_user_data接口获取
        :return:
        """
        log.debug(f"开始正式提交导入客户信息")
        path = "/ugreen/v1/user/import/commit"
        data = {'force_change_pwd': force_change_pwd,'overwrite':overwrite,'list':list}
        # data = {"force_change_pwd": False, "overwrite": False, "list": [
        #     {"uid": 0, "ugreen_no": 0, "icon_modify_time_sec": 0, "invite": False, "account_type": 0,
        #      "otp_info": {"issuer": "", "account": "", "secret": "", "status": 0, "urgent_email": ""}, "sex": 0,
        #      "cloud_backup": False, "role": "admin", "auth_list": None, "enable_change_pwd": False,
        #      "deny_change_pwd": False, "enable_home_dir": False, "username": "导入用户3", "password": "Aa123456@",
        #      "nickname": "", "phone": "", "email": "", "description": "", "expire_time": 0, "expire_date": "",
        #      "is_expired": False, "mobile_guide": False, "dir_quota": 0, "unit": 0, "status": True, "valid": True,
        #      "err_field": "", "err_tip": "", "line_number": 2}]}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在正式提交导入客户信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_import_state(self):
        """
        获取导入客户信息的状态
        :return:导入客户信息的状态及客户列表
        """
        log.debug(f"开始获取导入客户信息的状态")
        path = "/ugreen/v1/user/import/state"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取导入客户信息的状态过程中出现异常，异常信息: {e}")
            raise

    def check_import_state(self, timeout=60):
        """
        检查导入客户信息是否完成
        """
        log.debug("开始检查导入客户信息是否完成")
        elapsed_time = 0  # 已过去的时间，用更具描述性的变量名
        check_interval = 5  # 检查间隔时间，提取为变量方便后续修改

        try:
            while elapsed_time < timeout:
                log.debug(f"已过去 {elapsed_time} 秒，进行第 {elapsed_time // check_interval + 1} 次检查")
                import_status = self.get_import_state().get('is_running')
                if import_status is False:
                    log.info("导入客户信息已完成")
                    return True
                log.debug(f"导入仍在进行中，等待 {check_interval} 秒后再次检查")
                time.sleep(check_interval)
                elapsed_time += check_interval

            log.warning(f"在 {timeout} 秒内未完成导入客户信息的操作")
            return False

        except Exception as e:
            log.error(f"在检查导入客户信息是否完成过程中出现异常，异常信息: {e}", exc_info=True)
            raise


if __name__ == "__main__":
    login = Login(config_name=config_name)
    token = login.login()
    user = UserApi(token)
    uid = 1000
    user_info = user.get_user_name_list()
    print(user_info)
    # target_date = datetime(2025, 2, 28)
    # print(target_date)
